package com.sinoglobal.wallet.activity;

import com.sinoglobal.wallet.R;
import com.sinoglobal.wallet.activity.W_SinoBaseActivity.DialogOnClickListener;
import com.sinoglobal.wallet.api.RemoteImpl;
import com.sinoglobal.wallet.entity.W_DynamicKeyEntity;
import com.sinoglobal.wallet.entity.W_VerifyPassVo;
import com.sinoglobal.wallet.task.MyAsyncTask;
import com.sinoglobal.wallet.util.LogUtils;
import com.sinoglobal.wallet.view.DialogOfSetting;
import com.sinoglobal.wallet.widget.WGridPasswordView;
import com.sinoglobal.wallet.widget.WGridPasswordView.PasswordListener;
import com.sinoglobal.wallet.widget.KeyboardUtil;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager.LayoutParams;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 
 * @author lijingjing
 * @createdate 2015-10-31 上午10:05:31
 * @Description: TODO(输入支付密码)
 */
public class W_OrderPayActivity extends Activity implements OnClickListener{
	protected static final String TAG = W_OrderPayActivity.class.getSimpleName();
	private ImageView orderPay_edit;
	private RelativeLayout findPassword;
	private WGridPasswordView orderPay_password;
	private TextView orderPay_chanceTv, order_pay_money;
	private W_OrderPayActivity context, act;
	private int chanceId = 5;
	private int num = 0;
	private String key_id, key_key;
	private boolean DyncFlag = true;//只允许付款一次的的标识；
	@SuppressLint("NewApi")
	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		act = context = this;
		setContentView(R.layout.wallet_order_pay_activity);
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			this.setFinishOnTouchOutside(false);
		}

		//适配自定义键盘和布局
		WindowManager m = getWindowManager();
		Display d = m.getDefaultDisplay();
		LayoutParams p = getWindow().getAttributes();
		p.width = (int) (d.getWidth() * 1.0);
		getWindow().setAttributes(p);
		init();
	}
	private void init(){
		orderPay_edit = (ImageView) findViewById(R.id.orderPay_edit);
		findPassword = (RelativeLayout) findViewById(R.id.findPassword);
		orderPay_password = (WGridPasswordView) findViewById(R.id.orderPay_password);
		orderPay_chanceTv = (TextView) findViewById(R.id.orderPay_chanceTv);
		order_pay_money = (TextView) findViewById(R.id.order_pay_money);
		orderPay_edit.setOnClickListener(this);
		findPassword.setOnClickListener(this);
		
		if("WD".equals(getIntent().getStringExtra("Type"))){
			String money = getIntent().getStringExtra("Money");
			
			double payMoney = Double.parseDouble(money.toString());
			order_pay_money.setText("￥" + String.format("%.2f", payMoney));
			Log.d(".....", order_pay_money.getText().toString() + "...");
		}
		if("GOOD".equals(getIntent().getStringExtra("Type"))){
			String money = getIntent().getStringExtra("Money");
			Log.d(".....", money + "...");
			double payMoney = Double.parseDouble(money.toString());
			order_pay_money.setText("￥" + String.format("%.2f", payMoney));
		}
		
		orderPay_password.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				LogUtils.v("act---------------"+act);
				KeyboardUtil keyUtil = new KeyboardUtil(act, context, orderPay_password.getEditText());
				orderPay_password.setKeyUtil(keyUtil);
				keyUtil.showKeyboard();
				return false;
			}
		});	
		KeyboardUtil keyUtil = new KeyboardUtil(act, context, orderPay_password.getEditText());
		orderPay_password.setKeyUtil(keyUtil);
		keyUtil.showKeyboard();
		
		orderPay_password.setPasswordListener(new PasswordListener() {

			private String oldPwd = "";

			@Override
			public void setPassWord(String pwd) {
				Log.d(TAG, pwd);
				int a = chanceId - num;
			//	LogUtils.v("chanceId-----" + chanceId + "num----------" + num + "差值===========" + a +"-DyncFlag-"+DyncFlag);
				if (pwd.length() == 6 && chanceId - num > 0 && DyncFlag) {
					DyncFlag = false;
					oldPwd = pwd;
					getDynamickey();
				}
				if (num == 5) {
					showDialog(W_OrderPayActivity.this, "提示", "您今日密码输入次数超限，密码被锁定，请于2小时候后再尝试", "返回", R.color.w_c7, "", R.color.w_c14, false,
							new DialogOnClickListener() {

								@Override
								public void onSure(View v) {
									if("GOOD".equals(getIntent().getStringExtra("Type"))){
										sendDumpling_MakenumBroadcast();;//发送到捞一捞包饺子余额支付所需要的密码
									}
									finish();
								}

								@Override
								public void onCancle(View v) {
								}

							});
				}
			}
		});
	}
	@Override
	public void onClick(View v) {
		int id = v.getId();
		if(id == R.id.orderPay_edit){
			showDialog(W_OrderPayActivity.this, "提示", "是否取消支付？",
					"是",R.color.w_c14, "否",R.color.w_c14,true,new DialogOnClickListener() {

				@Override
				public void onSure(View v) {
//					Toast.makeText(OrderPayActivity.this, "是", Toast.LENGTH_SHORT).show();
					finish();
				}

				@Override
				public void onCancle(View v) {
//					Toast.makeText(OrderPayActivity.this, "否", Toast.LENGTH_SHORT).show();
				}
			});
		}else if(id == R.id.findPassword){
			Bundle find_bundle = new Bundle();
			find_bundle.putString("title_flag", "4");
			goIntent(W_PayPasswordActivity.class, find_bundle);
			W_OrderPayActivity.this.finish();
		}
	}
	public void goIntent(Class<?> toClsActivity, Bundle bundle) {
		Intent intent = new Intent(this, toClsActivity);
		if (bundle != null) {
			intent.putExtras(bundle);
		}
		startActivity(intent);
	}
	/** 显示Dialog 提示框,无需调用dialog.dismiss方法
     * @param message dialog的提示消息
     * @param sureText dialog确定按键的text文本
     * @param cancelText dialog取消按键的text文本
     * @param listener dialog的监听
     */
    public void showDialog(Context context,String title, String message,String sureText, int sureColor, String cancelText,int cancelColor,boolean isShowCancel ,final DialogOnClickListener listener){
        if(message==null){
            throw new NullPointerException("提示框消息不能为空");
        }
        if(sureText==null||sureText.equals("")){
            sureText = "确定";
        }
        if(cancelText==null||cancelText.equals("")){
            cancelText = "取消";
        }
         final DialogOfSetting mDialog = new DialogOfSetting(context);
        mDialog.setmMessage(message);
        mDialog.setmTitle(title);
        mDialog.setShowBtn(isShowCancel);
        if(!isShowCancel){
            mDialog.mConfirm.setText(sureText);
            mDialog.mConfirm.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(listener!=null){
                        listener.onSure(view);
                    }
                    mDialog.dismiss();
                    W_OrderPayActivity.this.finish();
                }
            });
        }
        mDialog.mCancle.setText(cancelText);
        mDialog.mCancle.setTextColor(getResources().getColor(cancelColor));
        mDialog.mSure.setText(sureText);
        mDialog.mSure.setTextColor(getResources().getColor(sureColor));
//        mDialog.mSure.setBackgroundResource(sureBackColor);
//        mDialog.mSure.setBackgroundColor(sureBackColor);
        mDialog.mCancle.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if(listener!=null){
                    listener.onCancle(v);
                }
                mDialog.dismiss();
            }
        });
        mDialog.mSure.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if(listener!=null){
                    listener.onSure(v);
                }
                mDialog.dismiss();
            }
        });
        mDialog.show();
    }
    
  //获取秘钥
  	private void getDynamickey(){

  		MyAsyncTask<W_DynamicKeyEntity> task = new MyAsyncTask<W_DynamicKeyEntity>(true,this,true) {

  			@Override
  			public W_DynamicKeyEntity before(Void... params) throws Exception {
  				// TODO 测试接口
  				return RemoteImpl.getInstance().getDynamicKey();
  			}
  			@Override
  			public void after(W_DynamicKeyEntity result) {
  				key_id = result.getId();
  				key_key = result.getEncryptKey();
  				oldPassWord();
  			}

  			@Override
  			public void exception() {
  			}
  		};
  		task.execute();
  	
  	
  	}
    
	//验证支付密码接口
	private void oldPassWord(){

		MyAsyncTask<W_VerifyPassVo> task = new MyAsyncTask<W_VerifyPassVo>(false,this,true) {
			
			@Override
			public W_VerifyPassVo before(Void... params) throws Exception {
				// TODO 测试接口
				Log.d("。。。。。。。。。", key_key + "......" + key_id);
				return RemoteImpl.getInstance().verifyPassWord(W_OrderPayActivity.this,
						orderPay_password.getPassWord().toString(), key_id, key_key);
			}
			@Override
			public void after(W_VerifyPassVo result) {
				
				if (result.getCode().equals("100")) {
					if(result != null){
						if("GOOD".equals(getIntent().getStringExtra("Type"))){
							sendDumpling_MakepassBroadcast();//发送到捞一捞包饺子余额支付所需要的密码
						}else if("WD".equals(getIntent().getStringExtra("Type"))){
							
							sendWithdrawalBroadcast();//通知W_WithDrawalActivit调用提现方法；
						}


						finish();
					}
				} else if (result.getCode().equals("101")){
					Toast.makeText(W_OrderPayActivity.this, result.getMsg(), Toast.LENGTH_SHORT).show();
					DyncFlag = true;
				} else if (result.getCode().equals("102")){
					orderPay_password.resetPassword();
					num = result.getNum();
					int a = chanceId - num ;
					orderPay_chanceTv.setText("支付密码输入不正确，您还有" + a + "次机会");
					DyncFlag = true;
					if(num ==5){

						showDialog(W_OrderPayActivity.this, "提示", "您今日密码输入次数超限，密码被锁定，请于2小时候后再尝试", "返回", R.color.w_c7, "", R.color.w_c14, false,
								new DialogOnClickListener() {
									@Override
									public void onSure(View v) {
										if("GOOD".equals(getIntent().getStringExtra("Type"))){
											sendDumpling_MakenumBroadcast();;//发送到捞一捞包饺子余额支付所需要的密码
										}
										finish();
									}

									@Override
									public void onCancle(View v) {
									}
								});
						return;
					
					}
					LogUtils.v("支付密码输入不正确，您还有" + a + "次机会");
				}

			}
			@Override
			public void exception() {
			}
		};
		task.execute();

	}
	private void sendWithdrawalBroadcast() {
		Intent intent = new Intent();
		intent.setAction("com.sinoglobal.wallet.receiver.withdrawal");
		intent.putExtra("passWord", orderPay_password.getPassWord().toString());
		intent.putExtra("type", 101);
		sendBroadcast(intent);
	}
	private void sendDumpling_MakepassBroadcast() {
		Intent intent = new Intent();
		intent.setAction("com.sinoglobal.dumpling.receiver.passwordNum");
		intent.putExtra("passWord", orderPay_password.getPassWord().toString());
		intent.putExtra("type", 101);
		sendBroadcast(intent);
	}
	private void sendDumpling_MakenumBroadcast() {
		Intent intent = new Intent();
		intent.setAction("com.sinoglobal.dumpling.receiver.passwordNum");
		intent.putExtra("Num",num);
		intent.putExtra("type", 103);
		sendBroadcast(intent);
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		showDialog(W_OrderPayActivity.this, "提示", "是否取消支付？",
				"是",R.color.w_c14, "否",R.color.w_c14,true,new DialogOnClickListener() {
			@Override
			public void onSure(View v) {
				finish();
			}
			@Override
			public void onCancle(View v) {
			}
		});
	
		return super.onKeyDown(keyCode, event);
	}
}
